package com.studyhub.question.controller;

import com.studyhub.question.model.dto.AnswerCreateDTO;
import com.studyhub.question.model.dto.QuestionCreateDTO;
import com.studyhub.question.model.dto.QuestionQueryDTO;
import com.studyhub.question.model.vo.AnswerVO;
import com.studyhub.question.model.vo.QuestionVO;
import com.studyhub.question.service.AnswerService;
import com.studyhub.question.service.MailboxService;
import com.studyhub.question.service.QuestionService;
import com.studyhub.web.utils.UserAuthUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 问题控制器
 */
@RestController
@RequestMapping("/Pass/question")
@RequiredArgsConstructor
public class QuestionController {

    private final QuestionService questionService;
    private final AnswerService answerService;
    private final MailboxService mailboxService;

    // ==================== 问题相关接口 ====================
    
    /**
     * 发布问题
     */
    @PostMapping("/create")
    public Map<String, Object> createQuestion(@Valid @RequestBody QuestionCreateDTO createDTO) {
        Long questionId = questionService.createQuestion(createDTO);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "问题发布成功");
        result.put("questionId", questionId);
        return result;
    }
    
    /**
     * 分页查询问题列表
     */
    @GetMapping("/list")
    public Map<String, Object> getQuestionList(@Valid QuestionQueryDTO queryDTO) {
        Map<String, Object> result = questionService.getQuestionListWithPagination(queryDTO);
        
        // 将问题列表中的ID转换为字符串，避免JavaScript大整数精度问题
        List<QuestionVO> questionList = (List<QuestionVO>) result.get("list");
        if (questionList != null) {
            questionList.forEach(question -> {
                if (question.getQuestionId() != null) {
                    question.setQuestionIdStr(question.getQuestionId().toString());
                }
            });
        }
        
        result.put("success", true);
        return result;
    }
    
    /**
     * 获取问题详情
     */
    @GetMapping("/detail/{questionId}")
    public Map<String, Object> getQuestionDetail(@PathVariable Long questionId) {
        Map<String, Object> result = new HashMap<>();
        try {
            QuestionVO question = questionService.getQuestionDetail(questionId);
            List<AnswerVO> answers = answerService.getQuestionAnswers(questionId);
            
            // 将问题ID转换为字符串，避免JavaScript大整数精度问题
            if (question != null && question.getQuestionId() != null) {
                question.setQuestionIdStr(question.getQuestionId().toString());
            }
            
            // 为所有答案设置answerIdStr，避免JavaScript大整数精度问题
            if (answers != null && !answers.isEmpty()) {
                setAnswerIdStrForAnswers(answers);
            }
            
            result.put("success", true);
            result.put("question", question);
            result.put("answers", answers);
        } catch (RuntimeException e) {
            result.put("success", false);
            result.put("message", "问题不存在");
        }
        return result;
    }
    
    /**
     * 递归为答案列表设置answerIdStr
     */
    private void setAnswerIdStrForAnswers(List<AnswerVO> answers) {
        if (answers == null || answers.isEmpty()) {
            return;
        }
        
        for (AnswerVO answer : answers) {
            if (answer.getAnswerId() != null) {
                answer.setAnswerIdStr(answer.getAnswerId().toString());
            }
            
            // 递归处理子回复
            if (answer.getChildren() != null && !answer.getChildren().isEmpty()) {
                setAnswerIdStrForAnswers(answer.getChildren());
            }
        }
    }
    
    /**
     * 点赞/取消点赞问题
     */
    @PostMapping("/like/{questionId}")
    public Map<String, Object> likeQuestion(@PathVariable Long questionId, @RequestParam Boolean isLike) {
        questionService.likeQuestion(questionId, isLike);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", isLike ? "点赞成功" : "取消点赞成功");
        return result;
    }

    /**
     * 删除问题
     */
    @DeleteMapping("/delete/{questionId}")
    public Map<String, Object> deleteQuestion(@PathVariable Long questionId) {
        questionService.deleteQuestion(questionId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "问题删除成功");
        return result;
    }
    
    // ==================== 答案相关接口 ====================
    
    /**
     * 发布答案
     */
    @PostMapping("/answer/create")
    public Map<String, Object> createAnswer(@Valid @RequestBody AnswerCreateDTO createDTO) {
        Long answerId = answerService.createAnswer(createDTO);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "答案发布成功");
        result.put("answerId", answerId.toString()); // 转换为字符串避免精度丢失
        return result;
    }
    
    /**
     * 删除答案
     */
    @DeleteMapping("/answer/delete/{answerId}")
    public Map<String, Object> deleteAnswer(@PathVariable Long answerId) {
        answerService.deleteAnswer(answerId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "答案删除成功");
        return result;
    }
    
    /**
     * 点赞/取消点赞答案
     */
    @PostMapping("/answer/like/{answerId}")
    public Map<String, Object> likeAnswer(@PathVariable String answerId, @RequestParam boolean isLike) {
        // 将字符串类型的answerId转换为Long，处理前端传递的字符串ID
        Long answerIdLong = Long.parseLong(answerId);
        answerService.likeAnswer(answerIdLong, isLike);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", isLike ? "点赞成功" : "取消点赞成功");
        return result;
    }

    // ==================== 消息通知相关接口 ====================
    
    /**
     * 获取未读消息数量
     */
    @GetMapping("/mailbox/unread-count")
    public Map<String, Object> getUnreadCount() {
        Integer userId = UserAuthUtil.getUserId();
        Integer count = mailboxService.getUnreadCount(userId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("unreadCount", count);
        return result;
    }
    
    /**
     * 获取消息列表
     */
    @GetMapping("/mailbox/list")
    public Map<String, Object> getMessageList(@RequestParam(defaultValue = "1") Integer pageNum,
                                            @RequestParam(defaultValue = "10") Integer pageSize) {
        Integer userId = UserAuthUtil.getUserId();
        var messages = mailboxService.getUserMessages(userId, pageNum, pageSize);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", messages);
        result.put("pageNum", pageNum);
        result.put("pageSize", pageSize);
        return result;
    }
    
    /**
     * 标记消息为已读
     */
    @PostMapping("/mailbox/read/{mailboxId}")
    public Map<String, Object> markAsRead(@PathVariable Long mailboxId) {
        mailboxService.markAsRead(mailboxId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "标记已读成功");
        return result;
    }

    // ==================== 测试接口 ====================
    
    /**
     * 测试接口，获取当前登陆用户User_id
     */
    @RequestMapping("/test")
    public String test(){
        try {
            Integer userId = UserAuthUtil.getUserId();
            if (userId != null) {
                return "当前用户id为：" + userId;
            } else {
                return "当前用户id为：未登录用户";
            }
        } catch (Exception e) {
            return "当前用户id为：获取失败，可能未登录";
        }
    }
}
